package gmu.xytxl.util;

import static org.hamcrest.CoreMatchers.nullValue;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;


import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JDBCUtils {
	// 数据库连接池对象
	private static DataSource source = null;
			

	public static Connection conn = null;
	public static ResultSet resultSet = null;
	public static PreparedStatement preparedStatement = null;
	
	static {
		source = new ComboPooledDataSource("webDataSource");
	}

	//获取连接
	public static Connection getConnection() {

		try {
			if (conn == null|| conn.isClosed()) {
				//第一次获取conn
				//创建connection
				try {
					conn = source.getConnection();
					//将数据库连接和当前线程绑定
					System.out.println("获取一次连接"+conn.toString());
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

	//关闭连接
	public static void closeConnection(ResultSet rs,Statement st,Connection con){
		//获取当前线程的连接
		if (rs!=null) {
			try {
				rs.close();
				System.out.println("关闭st"+rs.toString());
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (st!=null) {
			try {
				st.close();
				System.out.println("关闭st"+st.toString());
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(con!=null){
			try {
				con.close();
				System.out.println("关闭一次连接"+con.toString());
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	//通用查询
	public static ResultSet findAll(String sql, List<Object> list) {
		conn = getConnection();
		try {
			preparedStatement = conn.prepareStatement(sql);
			if (list!=null) {
				for (int i = 0; i < list.size(); i++) {
					preparedStatement.setObject(i+1, list.get(i));
				}
			}
			resultSet = preparedStatement.executeQuery();
			return resultSet;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		
	}

	//通用其他操作
	public static boolean excuteSql(String sql,List<Object> list) {
		conn = getConnection();
		int result = 0;
		try {
			preparedStatement = conn.prepareStatement(sql);
			if(list!=null) {
				for(int i=0;i<list.size();i++) {
					preparedStatement.setObject(i+1, list.get(i));
				}
				result = preparedStatement.executeUpdate();
				closeConnection(null,preparedStatement,conn);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (result>0) {
			return true;
		}else {
			return false;
		}
	}

}
